const axios = require('axios')
import * as XLSX from 'xlsx';
const instance = axios.create({
    baseURL: location.origin,
    timeout: 10 * 1000,
    // responseType: 'blob',
    // responseType: 'binary',
});
instance.interceptors.response.use(function (response) {
    return response.data;
}, function (error) {
    return Promise.reject(error);
});
instance.interceptors.request.use((config) => {
    // console.log('config', config)
    return config
})
function listenerForBgRequst(e) {
    if (e.data.type === 'wt_bgRequest') {
        if (!e.data.for_tab_id) return console.log('没有for_tab_id，请求了也没用')
        instance(e.data.body).then(res => {
            console.log('res', res)
            if (res.code) {
                window.postMessage({
                    type_urs: 'wtbg',
                    type_page: 'pageMeat',
                    method: 'call_script_function_callback',
                    tab_id: e.data.for_tab_id,
                    data: res.data,
                    createTaskIdStr: e.data.createTaskIdStr || ''
                })
                return
            }
            if (e.data.body.url === 'compass_api/download_center/shop/download_file_sync') {
                const reader = new FileReader();

                reader.onload = function (ess) {
                    const data = new Uint8Array(ess.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const sheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[sheetName];
                    const jsonData = XLSX.utils.sheet_to_json(worksheet);
                    // console.log('表格数据', jsonData)
                    window.postMessage({
                        type_urs: 'wtbg',
                        type_page: 'pageMeat',
                        method: 'call_script_function_callback',
                        tab_id: e.data.for_tab_id,
                        data: jsonData,
                        createTaskIdStr: e.data.createTaskIdStr || ''
                    })
                };
                reader.readAsArrayBuffer(res);
                // dataFor = jsonData
                return
            }
            window.postMessage({
                type_urs: 'wtbg',
                type_page: 'pageMeat',
                method: 'call_script_function_callback',
                tab_id: e.data.for_tab_id,
                data: res,
                createTaskIdStr: e.data.createTaskIdStr || ''
            })
        })
    }
}
window.addEventListener('message', listenerForBgRequst)